import { NextResponse } from 'next/server';
import { query } from '@/utils/db';
import { RowDataPacket } from 'mysql2/promise';

/**
 * 政策列表API
 * GET /api/enterprise/policies
 * 参数:
 * - page: 页码 (默认1)
 * - limit: 每页条数 (默认10)
 * - category: 政策分类 (可选)
 * - search: 搜索关键词 (可选)
 */
export async function GET(request: Request) {
  try {
    console.log('开始处理政策列表请求');
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const category = searchParams.get('category');
    const search = searchParams.get('search');
    
    console.log('请求参数:', { page, limit, category, search });
    
    const offset = (page - 1) * limit;
    
    // 构建查询条件
    let whereClause = '1=1';
    const params: any[] = [];
    
    if (category && category !== '全部') {
      whereClause += ' AND category = ?';
      params.push(category);
    }
    
    if (search) {
      whereClause += ' AND (title LIKE ? OR summary LIKE ?)';
      params.push(`%${search}%`, `%${search}%`);
    }
    
    // 查询政策列表 - 直接将limit和offset作为字符串插入SQL中，而不是作为参数
    const policiesQuery = `
      SELECT 
        id, title, summary, source, publish_date, 
        original_url, category, tags, 
        key_points, requirements, created_at
      FROM enterprise_policies
      WHERE ${whereClause}
      ORDER BY publish_date DESC, id DESC
      LIMIT ${limit} OFFSET ${offset}
    `;
    
    console.log('执行SQL查询:', policiesQuery);
    console.log('SQL参数:', params);
    
    // 查询总数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM enterprise_policies
      WHERE ${whereClause}
    `;
    
    // 执行查询
    const policies = await query<RowDataPacket[]>(policiesQuery, params);
    console.log(`查询结果: 获取到 ${policies?.length || 0} 条政策数据`);
    
    const countResults = await query<RowDataPacket[]>(countQuery, params);
    console.log('计数查询结果:', countResults);
    
    // 安全处理计数结果
    let total = 0;
    let totalPages = 0;
    
    if (countResults && countResults.length > 0 && countResults[0].total !== undefined) {
      total = countResults[0].total;
      totalPages = Math.ceil(total / limit);
    } else {
      // 如果计数查询失败，使用当前查询结果长度作为总数
      total = policies?.length || 0;
      totalPages = 1;
    }
    
    console.log(`总记录数: ${total}, 总页数: ${totalPages}`);
    
    // 处理数据
    const formattedPolicies = policies.map(policy => {
      try {
        console.log(`处理政策ID ${policy.id}`);
        return {
          id: policy.id,
          title: policy.title || '',
          summary: policy.summary || '',
          source: policy.source || '',
          publishDate: policy.publish_date ? 
            new Date(policy.publish_date).toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            }).replace(/\//g, '-') : null,
          url: policy.original_url || '',
          category: policy.category || '',
          tags: policy.tags ? policy.tags.split(',') : [],
          keyPoints: policy.key_points ? JSON.parse(policy.key_points) : [],
          requirements: policy.requirements ? JSON.parse(policy.requirements) : [],
          createdAt: policy.created_at
        };
      } catch (err) {
        console.error(`处理政策数据出错(ID:${policy.id}):`, err);
        console.error('问题数据:', {
          key_points: policy.key_points,
          requirements: policy.requirements
        });
        // 返回一个安全的默认值
        return {
          id: policy.id,
          title: policy.title || '',
          summary: policy.summary || '',
          source: policy.source || '',
          publishDate: policy.publish_date ? 
            new Date(policy.publish_date).toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            }).replace(/\//g, '-') : null,
          url: policy.original_url || '',
          category: policy.category || '',
          tags: policy.tags ? policy.tags.split(',') : [],
          keyPoints: [],
          requirements: [],
          createdAt: policy.created_at
        };
      }
    });
    
    console.log('成功处理政策列表请求');
    return NextResponse.json({
      success: true,
      policies: formattedPolicies,
      page,
      limit,
      total,
      totalPages
    });
  } catch (error) {
    console.error('获取政策列表失败:', error);
    return NextResponse.json(
      { success: false, message: '获取政策列表失败', error: String(error) },
      { status: 500 }
    );
  }
} 